package com.woshengqile.api.controller;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.jfinal.aop.Before;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.woshengqile.Pageable;
import com.woshengqile.api.common.bean.DataResponse;
import com.woshengqile.api.common.bean.DatumResponse;
import com.woshengqile.api.interceptor.AccessInterceptor;
import com.woshengqile.cache.J2CacheKit;
import com.woshengqile.model.VideoInfo;
import com.woshengqile.model.VideoInfoCategory;
import com.woshengqile.model.VideoInfoTag;
import com.woshengqile.service.VideoInfoCategoryService;
import com.woshengqile.service.VideoInfoService;
import com.woshengqile.service.VideoInfoTagService;

import net.hasor.core.Inject;

/**
 * API - 视频分类
 * @author yzc
 */
@ControllerBind(controllerKey = "/api/videoInfoCategory")
@Before(AccessInterceptor.class)
public class VideoInfoCategoryController extends BaseAPIController {
	
	@Inject
	private VideoInfoCategoryService videoInfoCategoryService;
	@Inject
	private VideoInfoTagService videoInfoTagService;
	@Inject
	private VideoInfoService videoInfoService;
	
	/**
	 * 查找顶级分类
	 */
	public void findRoots() {
		List<VideoInfoCategory> videoInfoCategories = J2CacheKit.get("mobileVideoInfoCategoryRoots", "mobileVideoInfoCategoryRoots");
		if (CollectionUtils.isEmpty(videoInfoCategories)) {
			videoInfoCategories = videoInfoCategoryService.findRoots(null);
			
			convertVideoCategory(videoInfoCategories);
			J2CacheKit.put("mobileVideoInfoCategoryRoots", "mobileVideoInfoCategoryRoots", videoInfoCategories); 
		}
		renderJson(new DataResponse(videoInfoCategories));
	}
	
	/**
	 * 查找分类下视频
	 */
	public void findVideoInfos() {
		Long voidInfoCategoryId = getParaToLong("voidInfoCategoryId");
		Long voidInfoTagId = getParaToLong("voidInfoTagId");
		Integer pageNumber = getParaToInt("pageNumber", 1);
		Integer pageSize = getParaToInt("pageSize", Pageable.API_DEFAULT_PAGE_SIZE);
		
		// 缓存key
		String cacheKey = "key_" + voidInfoCategoryId + "_" + pageNumber + "_" + pageSize + "_" + (voidInfoTagId == null ? 0 : voidInfoTagId);
		Page<VideoInfo> page = J2CacheKit.get("mobileVideoInfos", cacheKey + "1");
		if (page == null) {
			// 分类
			VideoInfoCategory videoInfoCategory = videoInfoCategoryService.find(voidInfoCategoryId);
			if (videoInfoCategory == null) {
				renderArgumentError("没有找到该分类!");
				return;
			}
			
			Pageable pageable = new Pageable(pageNumber, pageSize);
			// 标签
			VideoInfoTag videoInfoTag = videoInfoTagService.find(voidInfoTagId);
			page = videoInfoService.findPage(videoInfoCategory, videoInfoTag, pageable);
			convertVideoInfo(page.getList());
			J2CacheKit.put("mobileVideoInfos", cacheKey, page);
		}
		renderJson(new DatumResponse(page));
	}

}
